<template>
  <div ref="chartRef" :style="{ height: height, width: width }" />
</template>

<script setup>
import * as echarts from "echarts";

const props = defineProps({
  title: String,
  width: String,
  height: String,
  chartsData: {
    type: Array,
    default: () => [],
  },
});

const legendData = computed(() => {
  if (!props.chartsData) return [];
  return props.chartsData.map((i) => i.name);
});

const chartRef = ref();

const initChart = () => {
  const myChart = echarts.init(chartRef.value);

  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b} : {c} ({d}%)",
    },
    legend: {
      left: "5%",
      top: "30%",
      itemGap: 20,
      orient: "vertical",
      data: legendData.value,
    },
    series: [
      {
        name: props.title,
        type: "pie",
        roseType: "radius",
        radius: [15, 95],
        center: ["50%", "38%"],
        data: props.chartsData,
        animationEasing: "cubicInOut",
        animationDuration: 1200,
        top: 50,
        left: 50,
      },
    ],
  };
  myChart.setOption(option);
};

watch(
  () => props.chartsData,
  (val) => {
    if (val?.length) initChart();
  },
  {
    immediate: true,
  }
);
</script>
